package com.hontech.bvapp2.ui.parts.setting

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import com.hontech.bvapp2.R
import com.hontech.bvapp2.device.DeviceConn
import com.hontech.bvapp2.ui.dialog.runProg
import com.hontech.bvapp2.ui.view.LabelSpinner
import com.hontech.bvapp2.utils.onClick
import com.hontech.bvapp2.utils.runOnUi
import com.hontech.bvapp2.utils.stringsById

class SerialPortParts(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_setting_serial_port, this)

        val sp = view.findViewById<LabelSpinner>(R.id.id_serial_port_sp)
        val btnOpen = view.findViewById<Button>(R.id.id_serial_port_btn_open)

        btnOpen.onClick {
            if (DeviceConn.isOpen()) {
                DeviceConn.close()
                btnOpen.text = "打开"
            } else {
                runProg("串口", "打开") {
                    DeviceConn.open(sp.selectText())
                    btnOpen.text = "关闭"
                }
            }
        }

        runOnUi {
            try {
                val ps = stringsById(R.array.serial_ports)
                DeviceConn.open(ps[0])
                btnOpen.text = "关闭"
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}